import {ref} from "vue";
import {getCategoryFilterAPI, getSubCategoryAPI} from "@/api/category.js";
import {useRoute} from "vue-router";

export const useSubCategory = () => {
  const route = useRoute()

  const data = ref({})
  const getSubCategoryData = async () => {
    const res = await getCategoryFilterAPI(route.params.subId)
    data.value = res.result
    console.log(data.value)
  }

  const form = ref({
    categoryId: route.params.subId,
    page: 1,
    pageSize: 20,
    sortField: 'publishTime'
  })

  const tableChange = async () => {
    subList.value = []
    isLoading.value = true
    const res = await getSubCategoryAPI(form.value)
    isLoading.value = false
    subList.value = [...subList.value, ...res.result.items]
  }

  const isLoading = ref(false);

  const subList = ref([])
  const isLoadingMore = ref(true)
  const loadMore = async () => {
    if (isLoadingMore.value) {
      form.value.page += 1
      isLoading.value = true
      const res = await getSubCategoryAPI(form.value)
      isLoading.value = false
      console.log(res.result)
      subList.value = [...subList.value, ...res.result.items]
      if (res.result.items.length === 0) {
        isLoadingMore.value = false
      }
      console.log('666')
    }
  }

  return {
    getSubCategoryData,
    route,
    form,
    isLoading,
    subList,
    tableChange,
    loadMore,
    data
  }
}
